package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Bean.*;
import com.example.demo.Mapper.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;

/**
 * @Author: Redi
 * @Date: 2021/8/31 10:38
 * @Description:
 */
@Service
public class ExperimentManagementService {

    @Autowired
    ExperimentManagementMapper experimentMapper;

    @Autowired
    ReportMapper reportMapper;

    @Autowired
    StudentClassMapper studentClassMapper;

    @Autowired
    DraftsMapper draftsMapper;

    @Autowired
    TeamExperimentMapper teamExperimentMapper;

    @Autowired
    BelongMapper belongMapper;

    @Autowired
    TeamMapper teamMapper;

    public Result getExperimentDetail(Integer id) throws Exception{
        Result result = null;
            Experiment experiment = experimentMapper.selectById(id);
            if (experiment != null) {
                result = new Result(200, experiment);
            } else {
                result = new Result(403, "获取失败！");
            }
        return result;
    }

    public Result modifyExperimentDetail(Experiment experiment) throws Exception{
        Result result = null;
            Integer r = experimentMapper.updateById(experiment);
            if (r >= 1) {
                result = new Result(200, "修改成功");
            } else {
                result = new Result(403, "修改失败！");
            }
        return result;
    }

    public Result addExperiment(Experiment experiment) throws Exception{
        Result result = null;
            Integer r = experimentMapper.insert(experiment);
            if (r >= 1) {
                result = new Result(200, "添加成功！");
            } else {
                result = new Result(403, "操作失败！");
            }
        return result;
    }

    public Result searchExperiment(Integer pageNum, Integer pageSize,String name) throws Exception{
        Result result = null;
            Map<String,Object> map = new HashMap<>();
            Page<Experiment> page = new Page<>(pageNum, pageSize);
            page = experimentMapper.selectPage(page,new QueryWrapper<Experiment>().like("name",name));
            List<Experiment> list = page.getRecords();
            Integer total = experimentMapper.selectList(new QueryWrapper<Experiment>().like("name",name)).size();
            map.put("page",pageNum);
            map.put("size",pageSize);
            map.put("total",total);
            map.put("totalPage",total%pageSize>=1 ? total/pageSize+1 : total/pageSize);
            map.put("list",list);
            if (list.size()!=0) {
                result = new Result(200, map);
            } else {
                result = new Result(403, "未找到相关实验！");
            }
        return result;
    }

    public Result deleteExperiment(Integer id) throws Exception{
        Result result = null;
            Integer r = experimentMapper.deleteById(id);
            if (r >= 1) {
                reportMapper.delete(new QueryWrapper<Report>().eq("experiment_id",id));
                result = new Result(200, "删除成功！");
            } else {
                result = new Result(403, "操作失败！");
            }
        return result;
    }

    public Result getPage(Integer pageNum, Integer pageSize, String courseId,String name) throws Exception{
        Result result = null;
            Map<String,Object> map =new HashMap<>();
            Page<Experiment> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Experiment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("course_id",courseId);
            if(name!=null)
                queryWrapper.like("name",name);
            page = experimentMapper.selectPage(page, queryWrapper);
            //total表示搜索的总数量，所以需要再进行一次索引
            Integer total = experimentMapper.selectList(queryWrapper).size();
            List<Experiment> records = page.getRecords();
            for (Experiment experiment:records) {
                Result submittedNums = getSubmittedNums(experiment.getExperimentId());
                Map<String,Integer> res=(Map<String,Integer>)submittedNums.getObj();
                experiment.setSubmitted(res.get("submitted"));
                experiment.setShould_submitted(res.get("should_submitted"));
            }
            map.put("page",pageNum);
            map.put("size",pageSize);
            map.put("total",total);
            map.put("totalPage",total%pageSize>=1 ? total/pageSize+1 : total/pageSize);
            map.put("list",records);
            result = new Result(200, map);
        return result;
    }

    public Result getTotalExperimentNum() throws Exception{
        Result result = null;
        Integer num = experimentMapper.selectCount(null);
        result = new Result(200, num);
        return result;
    }

    public Result getSubmittedNums(Integer id) throws Exception{
            Result result =null;
            Experiment experiment = experimentMapper.selectById(id);
            if(experiment==null){
                return new Result(403,"实验不存在");
            }
            Map<String,Integer> map = new HashMap<>();
            QueryWrapper<Report> reportQueryWrapper = new QueryWrapper<>();
            reportQueryWrapper.eq("experiment_id",id);
            Integer num = reportMapper.selectCount(reportQueryWrapper);
            List<TeamExperiment> teamExperiments = teamExperimentMapper.selectList(new QueryWrapper<TeamExperiment>().eq("experiment_id", id));
            int nums = 0;
            for (TeamExperiment teamExperiment : teamExperiments) {
                nums += belongMapper.selectCount(new QueryWrapper<Belong>().eq("group_id",teamExperiment.getGroupId()));
            }
            map.put("submitted",num);
            map.put("should_submitted", Integer.valueOf(nums));
            result = new Result(200,map);
        return result;
    }


    public Result getSubmittedReports(Integer pageNum,Integer pageSize,Integer experiment_id) throws Exception{
        if(experimentMapper.selectById(experiment_id)==null)
            return new Result(403,"实验不存在!");
            QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("experiment_id",experiment_id);
            Page<Report> page = new Page<>(pageNum,pageSize);
            page =reportMapper.selectPage(page,queryWrapper);
            List<Report> reports = page.getRecords();
            Integer total = reportMapper.selectCount(queryWrapper);
            if(total==0)
                return new Result(403,"未找到相关实验报告");
            Map<String,Object> res = new HashMap<>();
            res.put("page",pageNum);
            res.put("size",pageSize);
            res.put("list",reports);
            res.put("total",total);
            res.put("totalPage",total%pageSize>=1? total/pageSize+1 : total/pageSize);
            return new Result(200,res);
    }


    public Result reportGrade(Integer report_id,Float code,String comment) throws Exception{
        Result res = null;
            if(code<0 || String.valueOf(code).length()>10)
                return new Result(403,"数据不合法");
            Report report = reportMapper.selectById(report_id);
            if(report!=null){
                report.setCode(code);
                if(comment!=null)
                    report.setComment(comment);
                if(reportMapper.updateById(report)>0)
                    res = new Result(200,"评分成功");
                else
                    res = new Result(403,"评分失败");
            }
            else
                res = new Result(403,"评分失败");
        return res;
    }

    public Result saveAsDraft(Drafts drafts) throws Exception{
        Result result = null;
            if(draftsMapper.insert(drafts)>=1)
                result=new Result(200,"存为草稿成功");
            else
                result=new Result(403,"存为草稿失败");
        return result;
    }

    public Result publishTask(String courseId, Integer draftId, List<Integer> groupIds) throws Exception{
        Drafts drafts = draftsMapper.selectById(draftId);
        if(drafts==null)
            return new Result(403,"找不到该草稿");
        Experiment experiment=null;
            experiment=new Experiment();
            experiment.setDraftId(draftId);
            experiment.setCourseId(courseId);
            experiment.setContent(drafts.getContent());
            experiment.setBeginTime(drafts.getBeginTime());
            experiment.setEndTime(drafts.getEndTime());
            experiment.setPath(drafts.getPath());
            experiment.setName(drafts.getName());
            experiment.setCreateTime(new Date(System.currentTimeMillis()));
            experiment.setUpdateTime(new Date(System.currentTimeMillis()));
            if(experimentMapper.insert(experiment)==0) {
                return new Result(403, "发布失败");
            }
        for (Integer groupId : groupIds) {
            teamExperimentMapper.insert(new TeamExperiment(groupId, experiment.getExperimentId()));
        }
        return new Result(200,"发布成功");
    }

    public Result draftUpdate(Drafts drafts) throws Exception{
            if(draftsMapper.updateById(drafts)>=1)
                return new Result(200,"编辑成功");
            else
                return new Result(403,"编辑失败");
    }

    public Result draftDelete(Integer draftId) throws Exception{
            if(draftsMapper.deleteById(draftId)>=1)
                return new Result(200,"删除成功");
            else
                return new Result(403,"删除失败");
    }

    public Result draftSearch(String name,Integer pageNum,Integer pageSize,String teacherUid) throws Exception{
        Result res = null;
            Page<Drafts> page=new Page<>(pageNum,pageSize);
            List<Drafts> list =null;
            QueryWrapper<Drafts> queryWrapper = new QueryWrapper<Drafts>().eq("teacher_uid", teacherUid);
            int total = 0;
            if(name==null){
                page=draftsMapper.selectPage(page,queryWrapper);
                list = page.getRecords();
                total=draftsMapper.selectCount(queryWrapper);
            }
            else{
                queryWrapper.like("name",name);
                page=draftsMapper.selectPage(page,queryWrapper);
                list = page.getRecords();
                total=draftsMapper.selectCount(queryWrapper);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("page",pageNum);
            map.put("size",pageSize);
            map.put("list",list);
            map.put("total",total);
            map.put("totalPage",total%pageSize>=1? total/pageSize+1 : total/pageSize);
            if(list.size()!=0)
                res=new Result(200,map);
            else
                res=new Result(200,"未找到相关草稿");
        return res;
    }

    public Result selectByName(String name,Integer pageNum,Integer pageSize,Integer experimentId) throws Exception{
        Result res = null;
        if(experimentMapper.selectById(experimentId)==null)
            return new Result(403,"实验不存在!");
            QueryWrapper<Report>queryWrapper=new QueryWrapper<>();
            if(name==null){
                queryWrapper.eq("experiment_id",experimentId);
            }
            else{
                queryWrapper.like("name",name);
                queryWrapper.eq("experiment_id",experimentId);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("pageNum",pageNum);
            map.put("pageSize",pageSize);
            Page<Report> page = new Page<>(pageNum,pageSize);
            page=reportMapper.selectPage(page,queryWrapper);
            List<Report> reports = page.getRecords();
            Integer total=reportMapper.selectCount(queryWrapper);
            map.put("total",total);
            map.put("list",reports);
            if(reports.size()!=0)
                res = new Result(200,map);
            else
                res = new Result(403,"未找到相关实验报告");
        return res;
    }

    public Result experimentScaleModify(Integer experimentId,Double scale) throws Exception{
        Result res = null;
        if(scale > 1.0){
            res=new Result(403,"数据不合法");
            return res;
        }
            Experiment experiment = experimentMapper.selectById(experimentId);
            if(experiment==null)
                res=new Result(403,"实验不存在!");
            else{

                experiment.setScale(scale);
                if(experimentMapper.updateById(experiment)>0)
                    res=new Result(200,"修改成功");
                else
                    res=new Result(403,"修改失败");
            }
        return res;
    }

    public Result published(Integer draftId, String crouseId) throws Exception{
        Result result;
            List<TeamExperiment> experiment_ids = teamExperimentMapper.selectList(new QueryWrapper<TeamExperiment>().eq("draft_id", draftId));
            List<Integer> groupIds = new ArrayList<>();
            for (TeamExperiment experiment_id : experiment_ids) {
                groupIds.add(experiment_id.getGroupId());
            }
            List<Team> teams = teamMapper.selectList(new QueryWrapper<Team>().in("group_id", groupIds).eq("course_id", crouseId));
            result = new Result(200, teams);
        return result;
    }
}
